/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package medialibrary.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceUnit;
import javax.persistence.Query;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.transaction.UserTransaction;
import medialibrary.persistence.*;

/**
 *
 * @author user
 */
@WebServlet(name="BorrowReserveServlet", urlPatterns={"/BorrowReserve"})
public class BorrowReserveServlet extends HttpServlet {
    @PersistenceUnit
    //The emf corresponding to 
    private EntityManagerFactory emf;  
    
    @Resource
    private UserTransaction utx;

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        assert emf != null;  //Make sure injection went through correctly.
        EntityManager em = null;
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
             
            int isbn    = Integer.parseInt(request.getParameter("isbn"));
            int memberId = Integer.parseInt(request.getParameter("memberid"));
       
        
         try {   
             
            utx.begin();
            
            em = emf.createEntityManager(); 
            Oeuvre o = em.find(Oeuvre.class, isbn);
            Membre m = em.find(Membre.class, memberId);
            
            out.println(o.getAuthor());
            out.println(m.getLogin());
            
            Query itemQuery = em.createQuery("select i from Item i where i.oeuvreISBN = :isbn");
            itemQuery.setParameter("isbn", o);
            List<Item> itemList = itemQuery.getResultList();
            Item i = null;
            if(itemList.size() > 0)
                i = (Item) itemList.get(0);
            else
                response.sendRedirect(response.encodeRedirectURL("/MediaLibrary/MemberUIServlet") );
                    
                      
            if(o.getDisponibility()==0) {
                out.println("Cet article n'est pas disponible, il vous sera réservé");
                Date d1 = new Date(System.currentTimeMillis());
                //calendar.add(calendar.MONTH, 1);
                Date d2 = calendar.getTime();
                Reservation reservation = new Reservation(d1, d1, m, i);
                em.persist(reservation);
                
            } else {
                out.println("Cet article est disponible, vous pouvez passer le récuperer");
                Date d1 = new Date(System.currentTimeMillis());
                //calendar.add(calendar.MONTH, 1);
                Date d2 = calendar.getTime();
                Administrator admin = em.find(Administrator.class, 1);
                Borrowing borrowing = new Borrowing(d1, d1, false, m, i, admin); 
                em.persist(borrowing);
                o.setDisponibility(o.getDisponibility()-1);
                }
            
            utx.commit();
            
            response.sendRedirect(response.encodeRedirectURL("/MediaLibrary/MemberUIServlet") );
            
                  
        } catch (Exception ex) {
            response.sendRedirect(response.encodeRedirectURL("/MediaLibrary/MemberUI") );
            out.println(ex.getLocalizedMessage());
            throw new ServletException(ex);
            
        } finally {            
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
